import {Component, OnInit, OnDestroy} from "@angular/core";
import {Hero} from "./Hero";
import {HeroService} from "./hero.service";
import {Router, ActivatedRoute} from "@angular/router";
import {Store} from "./store";
import {Subscription} from "rxjs";

@Component({
  selector: 'my-heroes',
  templateUrl: 'app/heroes.component.html',
  styleUrls: ['app/heroes.component.css']
})
export class HeroesComponent implements OnInit, OnDestroy {
  private _sub: Subscription
  // heroes: Hero[]
  selectedHero: Hero

  title = 'Tour of Heroes'
  hero: Hero = {
    id: 1,
    name: 'windstorm'
  }

  isSelected(hero: Hero) {
    return hero === this.selectedHero
  }

  constructor(private router: Router,
              private route: ActivatedRoute,
              private heroService: HeroService,
              private store: Store) {
  }

  ngOnInit() {
    this._sub = this.route.params.subscribe(params => {
      this.getHeroes(+params['id'])
    })
  }

  ngOnDestroy() {
    this._sub.unsubscribe()
  }

  getHeroes(selectedId) {
    this.heroService.getHeroes().then(heroes => {
      // this.heroes = heroes
      this.selectedHero = heroes.find(hero => hero.id === selectedId)
    })
  }

  deleteHero(hero: Hero) {
    this.heroService.deleteHero(hero)
  }

  newHero() {
    this.heroService.createHero()
  }

  clearHeroes() {
    this.heroService.clearHeros()
  }

  resetHeroes() {
    this.heroService.resetHeroes()
  }

  onSelect(hero: Hero) {
    this.selectedHero = hero
  }

  gotoDetail() {
    this.router.navigate(['/hero', this.selectedHero.id])
  }
}
